﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;


namespace LTorrent.Torrent.File
{
    #region BDictionary

    /// <summary>
    /// Dictionary
    /// start - 'd'
    /// end - 'e'
    /// Example - d2:hi7:goodbyee => ("hi" => "goodbye")
    /// </summary>
    public class BDictionary
    {
        protected List<BElement> FirstItem = null;
        protected List<BElement> SecondItem = null;

        public BDictionary()
        {
            FirstItem = new List<BElement>();
            SecondItem = new List<BElement>();
        }

        public int Count
        {
            get
            {
                return FirstItem.Count;
            }
        }
        /// <summary>
        /// index
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public BElement[] this[int index]
        {
            get
            {
                if (FirstItem.Count > index)
                {
                    BElement[] Items = new BElement[2];
                    Items[0] = FirstItem[index];
                    Items[1] = SecondItem[index];
                    return Items;
                }
                return new BElement[2];
            }
            set
            {
                if (FirstItem.Count > index)
                {
                    FirstItem[index] = value[0];
                    SecondItem[index] = value[1];
                }
                else
                {
                    FirstItem.Add(value[0]);
                    SecondItem.Add(value[1]);
                }
            }
        }
        /// <summary>
        /// Adds new item to dictionary
        /// </summary>
        /// <param name="First">First Item</param>
        /// <param name="Second">Second Item</param>
        public void Add(BElement First, BElement Second)
        {
            FirstItem.Add(First);
            SecondItem.Add(Second);
        }

        public void Serialize(BinaryWriter outStream)
        {
            outStream.Write('d');
            for (int index = 0; index < Count; index++)
            {
                this[index][0].Serialize(outStream);
                this[index][1].Serialize(outStream);
            }
            outStream.Write('e');
        }
    }
    #endregion
}
